package com.ljx.sso.config;

import com.ljx.sso.service.UserService;
import com.ljx.sso.vo.MyUser;
import com.ljx.utils.JwtUtil;
import com.ljx.vo.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author LJX
 * @Description: TODO
 * @Date: 2023/2/22 20:47
 * @Version 1.0
 */
@Configuration
public class MySecurity extends WebSecurityConfigurerAdapter {

	@Autowired
	private UserService userService;

	@Autowired
	private StringRedisTemplate redisTemplate;
	@Bean
	public PasswordEncoder passwordEncoder() {
		//加盐加密: 原密码+盐===>哈希加密===>密文
		//   原密码===>哈希加密===>密文 [存储大量常见的密文]
		//123456+随机产生盐===>密文
		return new BCryptPasswordEncoder();
	}


	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
	}


	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.formLogin()
				.successHandler(successHandler())
				.failureHandler(failureHandler())
				.loginProcessingUrl("/login").permitAll();

		http.cors();
		http.csrf().disable();
		http.authorizeRequests().anyRequest().authenticated();

	}

	private AuthenticationSuccessHandler successHandler() {
		return (request, response, authentication) -> {
			response.setContentType("application/json;charset=utf-8");
			PrintWriter writer = response.getWriter();
			//获取账号和权限
			//获取账号和权限
			MyUser principal = (MyUser)authentication.getPrincipal();
			String username = principal.getUsername();
			String loginType = principal.getLoginType();
			Collection<String> authorities = authentication.getAuthorities().stream().map(item->item.getAuthority()).collect(Collectors.toList());
			//根据账号和权限生产token;
			Map<String,Object> map=new HashMap<>();
			map.put("username",username);
			if(loginType!=null){
				map.put("loginType",loginType);
			}
			map.put("authorities",authorities);
			String token = JwtUtil.createJWT(map);

			//存入redis中。
			redisTemplate.opsForValue().set(token,"",1, TimeUnit.DAYS);

			Result<String> result=new Result<>(2000,"登录成功",token);
			String jsonString = JSON.toJSONString(result);

			writer.print(jsonString);
			writer.flush();
			writer.close();
		};
	}

	private AuthenticationFailureHandler failureHandler() {
		return (request, response, e) -> {
			response.setContentType("application/json;charset=utf-8");
			PrintWriter writer = response.getWriter();

			Result<String> result=new Result<>(5000,"登录失败 或者正在审核...");
			String jsonString = JSON.toJSONString(result);

			writer.print(jsonString);
			writer.flush();
			writer.close();
		};
	}

	public static void main(String[] args) {
//		BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
//		System.out.println(passwordEncoder.encode("123456"));

//		boolean b = JwtUtil.verifyToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2Nzc3NTMxODAsImlhdCI6MTY3NzY2NjgzNCwidXNlcmluZm8iOnsiYXV0aG9yaXRpZXMiOlsiYnVzaW5lc3M6YXBwZWFsIiwiYnVzaW5lc3M6ZW50ZXIiLCJidXNpbmVzczpleGFtaW4iLCJnb29kczpicmFuZCIsImdvb2RzOmNoZWNrIiwiZ29vZHM6ZGVwb3NpdCIsImdvb2RzOnNvcnQiLCJob21lOmZvb3QiLCJob21lOmhlYWROYXYiLCJob21lOmx1bmJvIiwiaG9tZTp5b3VxaW5nIiwiaG9tZTp6aHVhbnF1IiwibG9nOmxvZyIsIm1lbnU6bGlzdCIsInJvbGU6bGlzdCIsInRvdGFsOmJ1c2luZXNzIiwidG90YWw6cHJpY2UiLCJ0b3RhbDp1c2VyIiwidXNlcjpsaXN0IiwidXNlckluZm86bGlzdCJdLCJ1c2VybmFtZSI6ImxqeCJ9fQ.upcXg_2l1P7rez6t9LJYYkUxpmln-m6Ubv9zHQYNwyM");
//		System.out.println(b);
	}
}
